package ruler.rules.activities;

import java.util.ArrayList;
import java.util.Collections;

import ruler.main.R;
import ruler.main.WifiGPSRulerApplication;
import ruler.rules.Rule;
import ruler.rules.Rule.DEVICE_TYPE;
import ruler.rules.Rule.RULE_TYPE;
import ruler.rules.appRunningRule;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RuleEditorActivity extends Activity {

	TextView editTextName;
	TextView editTextDescription;
	RadioButton checkBoxGPS;
	RadioButton checkBoxWifi;
	RadioButton radioButtonEnable;
	RadioButton radioButtonDisable;
	RadioButton radioButtonInstalledApps;
	Spinner spinnerInstalledApps;
	RadioButton radioButtonRunningServices;
	Spinner spinnerRunningServices;
	CheckBox checkBoxWhenIsValid;
	Button saveChanges;

	private String[] installedApps;
	private String[] runningServices;

	private WifiGPSRulerApplication app;
	private Rule originalRule;
	private Rule newRule;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rule_editor);
		app = (WifiGPSRulerApplication) getApplication();

		this.newRule = new appRunningRule();

		editTextName = (TextView) findViewById(R.id.editTextName);
		editTextDescription = (TextView) findViewById(R.id.editTextDescription);
		checkBoxGPS = (RadioButton) findViewById(R.id.radioButtonGPS);
		checkBoxWifi = (RadioButton) findViewById(R.id.radioButtonWifi);
		radioButtonEnable = (RadioButton) findViewById(R.id.radioButtonEnable);
		radioButtonDisable = (RadioButton) findViewById(R.id.radioButtonDisable);
		radioButtonInstalledApps = (RadioButton) findViewById(R.id.radioButtonInstalledApps);
		spinnerInstalledApps = (Spinner) findViewById(R.id.spinnerInstalledApps);
		radioButtonRunningServices = (RadioButton) findViewById(R.id.radioButtonRunningServices);
		spinnerRunningServices = (Spinner) findViewById(R.id.spinnerRunningServices);
		checkBoxWhenIsValid = (CheckBox) findViewById(R.id.checkBoxWhenIsRunning);
		saveChanges = (Button) findViewById(R.id.buttonSave);
		
		saveChanges.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				saveChanges();
			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null)
			this.originalRule = (Rule) extras.getParcelable("PARCEABLE_RULE");

		installedApps = AppsLists.getInstalledApps(this);
		runningServices = AppsLists.getRunningServices(this);
		
		if (this.originalRule != null) {
			this.newRule = new appRunningRule(this.originalRule);
			initComponentes();
			selectSpinners();
		} else {
			initSpinners();
			checkBoxGPS.setChecked(true);
			radioButtonEnable.setChecked(true);
			radioButtonInstalledApps.setChecked(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_rules_editor, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.saveChanges:
			saveChanges();
			break;
		}
		return true;
	}

	private void initSpinners() {
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, installedApps);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerInstalledApps.setAdapter(adapter1);

		ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, runningServices);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerRunningServices.setAdapter(adapter3);
	}

	private void saveChanges() {
		this.newRule.setName(editTextName.getText().toString());
		this.newRule.setDescription(editTextDescription.getText().toString());
		if (checkBoxGPS.isChecked())
			this.newRule.setDeviceType(DEVICE_TYPE.GPS);
		if (checkBoxWifi.isChecked())
			this.newRule.setDeviceType(DEVICE_TYPE.WIFI);
		if (radioButtonEnable.isChecked())
			this.newRule.setDeviceEnable(true);
		if (radioButtonDisable.isChecked())
			this.newRule.setDeviceEnable(false);
		if (radioButtonInstalledApps.isChecked()) {
			this.newRule.setRuleType(RULE_TYPE.APP);
			this.newRule.setPackageName(spinnerInstalledApps.getSelectedItem()
					.toString());
		}
		if (radioButtonRunningServices.isChecked()) {
			this.newRule.setRuleType(RULE_TYPE.SERVICE);
			this.newRule.setPackageName(spinnerRunningServices
					.getSelectedItem().toString());
		}
		if (checkBoxWhenIsValid.isChecked())
			this.newRule.setWhenIsRunning(true);
		else
			this.newRule.setWhenIsRunning(false);
		if (this.newRule.getDeviceType() != null) {
			app.removeRule(this.originalRule);
			if (!this.newRule.isInConflictWithOne(app.getAllRules())) {
				app.addRule(this.newRule);
				app.saveRules();
				finish();
			} else {
				app.addRule(this.originalRule);
				Toast.makeText(this, "The rule is in conflict with others.",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void initComponentes() {
		editTextName.setText(this.originalRule.getName());
		editTextDescription.setText(this.originalRule.getDescription());
		if (this.originalRule.getDeviceType() == Rule.DEVICE_TYPE.GPS) {
			checkBoxGPS.setChecked(true);
		} else {
			checkBoxWifi.setChecked(true);
		}
		if (this.originalRule.getDeviceEnable()) {
			radioButtonEnable.setChecked(true);
		} else {
			radioButtonDisable.setChecked(true);
		}
		checkBoxWhenIsValid.setChecked(this.originalRule.getWhenIsRunning());
	}

	private void selectSpinners() {
		String packageName = this.originalRule.getPackageName();
		if (this.originalRule.getRuleType() == Rule.RULE_TYPE.APP) {
			int position = getSpinnerPosition(installedApps, packageName);
			if (position == -1) {
				installedApps = addElement(this.originalRule.getPackageName(),
						installedApps);
				position = 0;
			}
			initSpinners();
			selectSpinner(radioButtonInstalledApps, spinnerInstalledApps, position);
		} else {
			int position = getSpinnerPosition(runningServices, packageName);
			if (position == -1) {
				runningServices = addElement(
						this.originalRule.getPackageName(), runningServices);
				position = 0;
			}
			initSpinners();
			selectSpinner(radioButtonRunningServices,spinnerRunningServices,position);
		}
	}
	
	private void selectSpinner(RadioButton radioButton, Spinner spinner, int position){
		radioButton.setChecked(true);
		spinner.setSelection(position);
		spinner.setSelected(true);
	}

	private int getSpinnerPosition(String[] list, String packageName) {
		int pos = 0;
		for (String item : list) {
			if (item.equals(packageName))
				return pos;
			pos++;
		}
		return -1;
	}

	private static String[] addElement(String newElement, String[] original) {
		ArrayList<String> list = new ArrayList<String>();
		Collections.addAll(list, newElement);
		for (String string : original) {
			Collections.addAll(list, string);
		}
		return list.toArray(new String[list.size()]);
	}

}
